package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.template.HuanXinTemplate;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void add(Long targetUserId, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("friendId").is(targetUserId));

        boolean exists = mongoTemplate.exists(query, Friend.class);
        if (!exists){
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(targetUserId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        }
        query = new Query();
        query.addCriteria(Criteria.where("userId").is(targetUserId).and("friendId").is(userId));
        boolean exists1 = mongoTemplate.exists(query, Friend.class);
        if (!exists1){
            Friend friend = new Friend();
            friend.setUserId(targetUserId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        }


    }

    @Override
    public PageResult people(Long userId,Integer page, Integer pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        int pages = (int) Math.ceil(count*1.0/pagesize);

        return new PageResult((int) count,pagesize,pages,page,friends);
    }
}
